package cn.chendd.example;

import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jci.compilers.CompilationResult;
import org.apache.commons.jci.compilers.JavaCompiler;
import org.apache.commons.jci.compilers.JavaCompilerFactory;
import org.apache.commons.jci.examples.serverpages.JspGenerator;
import org.apache.commons.jci.readers.FileResourceReader;
import org.apache.commons.jci.stores.FileResourceStore;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

/**
 * @author chendd
 * @date 2019/6/8 13:47
 * 编译JSP文件为Java再编译为Class
 */
public class JspClassCompiler extends TestCase {

    public void testJSPCompiler() throws Exception {

        String resourceName = "cn/chendd/examples/TestJSP.java";
        File sourceDir = new File("D:\\test\\compiler");
        File targetDir = new File("D:\\test\\compiler");
        JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
        JspGenerator transformer = new JspGenerator();
        File jspFileSource = new File(sourceDir , "cn/chendd/examples/test.jsp");
        byte bytes[] = transformer.generateJavaSource(resourceName, jspFileSource);
        FileUtils.writeStringToFile(new File(sourceDir , resourceName), new String(bytes));

        String sources[] = { resourceName };

        String jarPath = "C:\\Users\\chendd\\.m2\\repository\\javax\\servlet\\javax.servlet-api" +
                "\\3.0.1\\javax.servlet-api-3.0.1.jar";
        URL urls[] = new URL[]{
            new File(jarPath).toURI().toURL()
        };

        ClassLoader classloader = new URLClassLoader(urls);

        CompilationResult result = compiler.compile(sources, new FileResourceReader(sourceDir),
                new FileResourceStore(targetDir) , classloader);
        System.out.println(result.getErrors().length + " errors");
        System.out.println(Arrays.toString(result.getErrors()));
        System.out.println(result.getWarnings().length + " warnings");
    }

}
